package myJs.user

import argonaut.Argonaut._
import argonaut._
import myJs.FileSaver
import myJs.Implicits._
import myJs.Utils._
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.myPkg.jquery._
import myJs.myPkg._
import myJs.tool.Tool
import myJs.tool.Tool._
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.raw.{Blob, BlobPropertyBag}
import scalatags.Text.all
import scalatags.Text.all._
import shared.Pojo._
import shared.VarTool

import scala.collection.SeqMap
import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.scalajs.js.{Date, JSON}
import scala.scalajs.js.Dynamic.{global => g}

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("StepMissionResult")
object StepMissionResult extends SampleManagePlot with SampleManageHtml with SampleManageTool {

  val tableId = "table"
  val curTime = timeFormat(new Date())
  val strSiteNames = VarTool.autoSiteNames ::: VarTool.ySiteNames ::: VarTool.xSiteNames
  val allSiteNames = VarTool.allSiteNames
  var queryMap = Map[String, Any]()
  var select2Vs = js.Array[String]()
  val headerMap = SeqMap("id" -> "样品编号", "indexId" -> VarTool.indexStr, "sampleIntro" -> VarTool.sampleIntroStr,
    "gender" -> "性别", "kind" -> "类型", "containerName" -> "板号", "comment" -> VarTool.commentStr,
    "updateMission" -> "分析名称", "updateTime" -> "更新时间", "autosomalLociTyped" -> "Autosomal Loci Typed",
    "yLociTyped" -> "Y Loci Typed", "xLociTyped" -> "X Loci Typed", "isnpLociTyped" -> "iSNP Loci Typed",
    "interlocusBalance" -> "Interlocus Balance", "singleSource" -> "污染风险", "stepNum" -> "步数")
  var filterNonExist = false
  val exportDatModalId = s"exportDatModal"
  val exportAllDatModalId = "exportAllDatModal"
  val formId="form"

  @JSExport("init")
  def init = {
    refreshMissionInfo.map { dict =>
      val kitName = dict("kitName")
      initTable(kitName)
    }
    bootStrapValidator
    initFilterContent
    refreshView

    initStrTable
    initSnpDetailTable
    $("#myLoading").width($(".row-fluid").width())
    Tool.clickHide
    refreshKitName
    refreshStep
    refreshContainerName

    refreshTableData
    registerEvent
    $(s"#${exportAllDatModalId} #lblAddTitle").text("导出DAT文件")

    //    columnsSelectShow

  }

  def registerEvent={
    $(document.body).on("click", ".myExportAllDat", "", (y: Element) => {
      exportAllDat
    })
  }

  def refreshTableData = {
    val url = g.jsRoutes.controllers.StepMissionController.getMissionResultData().url.toString
    Ajax.get(url = s"${url}?missionId=${getMissionId}").map { xhr =>
      val data = xhr.responseText.toJArJDS
      $("#table").bootstrapTable("load", data)
    }

  }

  def refreshMissionInfo = {
    val url = g.jsRoutes.controllers.StepMissionController.getMissionById().url.toString
    Ajax.get(url = s"${url}?missionId=${getMissionId}").map { xhr =>
      val dict = JSON.parse(xhr.responseText).toJDS
      dict.foreach { case (k, v) =>
        $(s"#mission #${k}").text(v.toString)
      }
      val resultNum = dict("result").split(";").size - 1
      $("#resultNum").text(resultNum.toString)
      dict
    }
  }

  def getCurrentTime = {
    val url = g.jsRoutes.controllers.SampleController.getCurrentTime().url.toString
    Ajax.get(url = s"${url}").map { xhr =>
      xhr.responseText.toJDS("time")
    }
  }

  def refreshStep = {
    val map = Map(1 -> "一步", 2 -> "两步")
    val html = map.zipWithIndex.map { case ((v, showV), i) =>
      label(
        marginRight := 15,
        width := 150,
      )(input(
        `type` := "radio",
        name := "step",
        value := v,
        if (i == 0) checked else all.raw(""),
      )(showV)
      )
    }.mkString
    $("#steps").empty().html(html)
  }

  def refreshContainerName = {
    val inputName = "containerName"
    val url = g.jsRoutes.controllers.SampleController.getAllContainerName().url.toString
    Ajax.get(url = s"${url}").map { xhr =>
      val data = JSON.parse(xhr.responseText).toJArS.toList
      val array = ("" :: data).map { v =>
        js.Dictionary("text" -> v, "id" -> v)
      }
      val options = Select2Options.dictData(array.toJSArray)
      Tool.getInputByName(inputName).select2(options)
    }
  }

  def refreshView = {
    refreshBasicInfoView
    produceAutoStrSiteView
    produceYStrSiteView
    produceXStrSiteView
    produceISnpSiteView
    produceYSnpSiteView
    //    columnsSelectShow
  }

  def refreshKitName = {
    val names = VarTool.searchKitNames
    val html = names.zipWithIndex.map { case (vsName, i) =>
      label(
        marginRight := 15,
        width := 150,
      )(input(
        `type` := "radio",
        name := "kitName",
        value := vsName,
        if (i == 0) checked else all.raw(""),
      )(vsName)
      )
    }.mkString
    $(s"#${exportDatModalId} #kitNames").empty().html(html)
    $(s"#${exportAllDatModalId} #kitNames").empty().html(html)

  }

  def initSnpDetailTable = {
    val map = SeqMap(
      "genotype" -> "Allele Name",
      "typedAllele" -> "Typed Allele",
      "reads" -> "Reads"
    )
    val columnNames = map.keys.toJSArray
    val columns = columnNames.map { columnName =>
      val title = map.getOrElse(columnName, columnName)
      ColumnOptions.field(columnName).title(title).sortable(true)
    }
    val options = TableOptions.columns(columns)
    $("#snpModal #detailTable").bootstrapTable(options)
  }

  def clearSelect2 = {
    Tool.getInputByName("updateMission").select2Val(js.Array[String]())
  }

  def clearInput = {
    clearSelect2
    $(".filterInput").not(".select2Input").`val`("")
  }

  @JSExport("clearFilter")
  def clearFilter = {
    clearInput
    execFilter
  }

  def initStrTable = {
    val map = SeqMap(
      "genotype" -> "Allele Name",
      "typedAllele" -> "Typed Allele",
      "reads" -> "Reads",
      "repeatSeq" -> "Repeat Sequence"
    )
    val columnNames = map.keys.toJSArray
    val columns = columnNames.map { columnName =>
      val title = map.getOrElse(columnName, columnName)
      ColumnOptions.field(columnName).title(title).sortable(true)
    }
    val options = TableOptions.columns(columns)
    $(s"#locusModal #detailTable").bootstrapTable(options)
  }

  def dateInit = {
    val options = DatepickerOptions.format(Tool.pattern).language("zh-CN").autoclose(true).clearBtn(true)
    $(".myDatepicker").datepicker(options)
    $(".myDate").datepicker(options)
  }

  def refreshTable(f: () => js.Any = () => ()) = {
    assignQueryMap
    $("#table").bootstrapTable("refresh")
    $("#table").bootstrapTable("uncheckAll")
    f()
  }

  val operateColumn = js.Array(
    ColumnOptions.field("operate").title("操作").formatter(operateFmt).cellStyle(operateStyle).`class`("myOperate")
  )

  def getSeqDatas(rs: String) = {
    rs.decodeOption[List[CurSeqData]].getOrElse(Nil)
  }

  @JSExport("strDetailShow")
  def strDetailShow(str: String, locus: String, idStr: String) = {
    $(".id").text(idStr)
    val seqDatas = getSeqDatas(str)
    val modalId = "locusModal"
    $(".locus").text(locus)
    Tool.refreshTable(JSON.parse(str), $(s"#${modalId} #detailTable"))
    strDetailPlot(seqDatas)
    jQuery(s"#${modalId}").modal("show")
  }

  @JSExport("snpDetailShow")
  def snpDetailShow(str: String, locus: String, idStr: String) = {
    $(".id").text(idStr)
    val seqDatas = getSeqDatas(str)
    $(".locus").text(locus)
    val modalId = "snpModal"
    Tool.refreshTable(JSON.parse(str), $(s"#${modalId} #detailTable"))
    snpDetailPlot(seqDatas)
    jQuery(s"#${modalId}").modal("show")
  }

  def tbFmt(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[js.Any]) => {
    columnName match {
      case "updateMission" => {
        val url = g.jsRoutes.controllers.MissionController.missionSummaryBeforeByName().url.toString
        a(href := s"${url}?missionName=${v}", target := "_blank", v.toString).render
      }
      case "id" => {
        val detailUrl = g.jsRoutes.controllers.SampleController.sampleSummaryBefore().url.toString
        val hrefStr = s"${detailUrl}?id=${row("id")}&panel=${row("panel")}"
        a(href := s"${hrefStr}", target := "_blank", v.toString).render
      }
      case x if List("sampleIntro", "comment").contains(x) => {
        span(v.toString, title := v.toString)
      }
      case x if List("autosomalLociTyped", "yLociTyped", "xLociTyped", "isnpLociTyped").contains(x) => {
        val vStr = v.toString
        val dbs = vStr.split("/").map(_.toDouble)
        val rate = (dbs(0)) / (dbs(1))
        val imageStr = rate match {
          case x if x > 0.8 => ""
          case x if x > 0.5 && x <= 0.8 => "median"
          case x if x <= 0.5 => "low"
          case _ => ""
        }
        val imgHtml = if (imageStr.isBlank) {
          span()
        } else {
          img(src := s"/assets/images/${imageStr}.png", height := 14)
          //          span(img(src := s"/assets/images/median.png", height := 14))
        }
        span(imgHtml, span(verticalAlign := "middle", s"${v}")
        )
      }
      case x if allSiteNames.contains(x) => {
        if (v.isDdefined) {
          val dict = v.toJDJAn
          val locus = x
          val rawSeqs = dict("rawSeqs").toJArJDS
          val trueV = dict(VarTool.genotypeStr).toString
          val bgColor = dict("color").toString
          val rowHeight = 26
          val fSize = trueV.trim.size match {
            case x if x <= 5 => 12
            case x if x > 5 && x <= 9 => 8
            case x if x > 9 => 6
            case _ => 12
          }
          if (trueV.isEmpty) {
            div(width := "100%",
              trueV
            )
          } else if (VarTool.snpSiteNames.contains(locus)) {
            div(width := "100%",
              height := rowHeight,
              onclick := s"SampleManage.snpDetailShow('${JSON.stringify(rawSeqs)}','${locus}','${row("id")}')",
              cursor := "pointer",
              textAlign := "center",
              verticalAlign := "middle",
              backgroundColor := bgColor,
              div(
                lineHeight := s"${rowHeight}px",
                fontSize := s"${fSize}px",
                trueV)
            )
          } else if (dict.isDefinedAt(VarTool.qcStr)) {
            div(width := "100%",
              height := rowHeight,
              onclick := s"SampleManage.strDetailShow('${JSON.stringify(rawSeqs)}','${locus}','${row("id")}')",
              cursor := "pointer",
              title := s"${dict(VarTool.qcStr).toString}",
              textAlign := "center",
              verticalAlign := "middle",
              backgroundColor := bgColor,
              div(
                lineHeight := s"${rowHeight}px",
                fontSize := s"${fSize}px",
                trueV)
            )
          } else {
            div(width := "100%",
              height := rowHeight,
              onclick := s"SampleManage.strDetailShow('${JSON.stringify(rawSeqs)}','${locus}','${row("id")}')",
              cursor := "pointer",
              textAlign := "center",
              verticalAlign := "middle",
              backgroundColor := bgColor,
              div(
                lineHeight := s"${rowHeight}px",
                fontSize := s"${fSize}px",
                trueV)
            )
          }
        } else {
          div(width := "100%",
            textAlign := "center",
            div(
              "-"
            )
          )
        }

      }
      case _ => v
    }
  }

  def produceISnpSiteView = {
    val siteNames = VarTool.iSnpSiteNames
    val html = siteNames.zipWithIndex.map { case (vsName, i) =>
      label(
        marginRight := 15,
        width := checkWidth,
        cls := "myCheckbox"
      )(input(`class` := "iSnp",
        `type` := "checkbox",
        name := "columNames[]",
        value := vsName,
      )(vsName)
      )
    }.mkString
    $("#iSnpSite").empty().html(html)
  }

  def produceYSnpSiteView = {
    val siteNames = VarTool.ySnpSiteNames
    val html = siteNames.zipWithIndex.map { case (vsName, i) =>
      label(
        marginRight := 15,
        width := checkWidth,
        cls := "myCheckbox"
      )(input(`class` := "ySnp",
        `type` := "checkbox",
        name := "columNames[]",
        value := vsName,
      )(vsName)
      )
    }.mkString
    $("#ySnpSite").empty().html(html)
  }

  def produceXStrSiteView = {
    val siteNames = VarTool.xSiteNames
    val html = siteNames.zipWithIndex.map { case (vsName, i) =>
      label(
        marginRight := 15,
        width := checkWidth,
        cls := "myCheckbox"
      )(input(`class` := "xStr",
        `type` := "checkbox",
        name := "columNames[]",
        value := vsName,
      )(vsName)
      )
    }.mkString
    $("#xStrSite").empty().html(html)
  }

  def produceYStrSiteView = {
    val siteNames = VarTool.ySiteNames
    val html = siteNames.zipWithIndex.map { case (vsName, i) =>
      label(
        marginRight := 15,
        width := checkWidth,
        cls := "myCheckbox"
      )(input(`class` := "yStr",
        `type` := "checkbox",
        name := "columNames[]",
        value := vsName,
      )(vsName)
      )
    }.mkString
    $("#yStrSite").empty().html(html)
  }

  @JSExport("kitSelect")
  def kitSelect(kitName: String) = {
    val index = layer.load(0, Tool.layerOptions.shade(js.Array("0.1", "#fff")))
    val siteNames = VarTool.siteNamesMap.getOrElse(kitName, {
      kitName match {
        case "YARN" => VarTool.yarnYSiteNames ::: VarTool.ySnpSiteNames
        case "SETA" => VarTool.autoSiteNames ::: VarTool.setAYSiteNames ::: VarTool.xSiteNames ::: VarTool.iSnpSiteNames
        case "SETB" => VarTool.setBSiteNames
      }
    })
    $(":input[name='columNames[]']").not(".basicInfo").prop("checked", false)
    $(":input").filter { y: Element =>
      val v = $(y).myVal
      siteNames.contains(v)
    }.prop("checked", true)
    layer.close(index)
  }

  @JSExport("selectAll")
  def selectAll(kind: String = "") = {
    if (kind.nonBlank) {
      $(s":input.${kind}").prop("checked", true)
    } else {
      $(":input[name='columNames[]']").prop("checked", true)
    }
  }

  @JSExport("reverseSelect")
  def reverseSelect(kind: String = "") = {
    if (kind.nonBlank) {
      $(s":input.${kind}").each { (y: Element, i: Int) =>
        val b = $(y).prop("checked").asInstanceOf[Boolean]
        $(y).prop("checked", !b)
      }
    } else {
      $(":input[name='columNames[]']").each { (y: Element, i: Int) =>
        val b = $(y).prop("checked").asInstanceOf[Boolean]
        $(y).prop("checked", !b)
      }
    }
  }

  @JSExport("execColumnsSelect")
  def execColumnsSelect = {
    val columnNames = $(":input[name='columNames[]']:checked").mapElems { y =>
      $(y).`val`().toString
    }.toList
    jQuery("#modal").modal("hide")
    val options = getTableOptions(columnNames)
    $("#table").bootstrapTable("refreshOptions", options)
    initFilter
  }

  @JSExport("columnsSelectShow")
  def columnsSelectShow = {
    jQuery("#modal").modal("show")
  }

  @JSExport("execFilter")
  def execFilter = {
    showLoading
    fillConditionHtml
    allFilter
  }

  def registerFilter = {

    refreshUpdateMission

  }

  @JSExport("execSort")
  def execSort(y: Element) = {
    showLoading
    fillSortHtml(y)
    val iJq = $(y).find("i")
    val isAsc = !iJq.hasClass("fa-sort-alpha-desc")
    val order = if (!isAsc) {
      "desc"
    } else "asc"
    val fieldName = Tool.getFilterDataFieldName($(y).parents(".filterContent"))
    val faClass = if (isAsc) "fa-long-arrow-up" else "fa-long-arrow-down"
    $(s"button[filter-data-field=${fieldName}]").find(".afterSortFa")
      .removeClass("fa-long-arrow-up").removeClass("fa-long-arrow-down").
      addClass(faClass)
    $(".myLi").removeClass("active")
    $(y).addClass("active")
    hideFilterContent(y)
    refreshTable()

  }

  def allFilter = {
    assignQueryMap
    $("#table").bootstrapTable("refresh")
    clearSelect
  }

  def clearSelect = {
    $("#table").bootstrapTable("uncheckAll")
  }

  def onSort: js.Function = { (name: String, order: String) =>
    execFilter
  }

  def showLoading = {
    $("#myLoading").show()
  }

  def showLoadingF: js.Function = { () =>
    $("#myLoading").show()
  }

  def onLoadSuccess: js.Function = { () =>
    $("#myLoading").hide()
  }

  def expStyle(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[Any]) => columnName match {
    case x if List("sampleIntro", "comment").contains(x) => js.Dictionary("css" -> js.Dictionary(
      "overflow" -> "hidden", "white-space" -> "nowrap", "text-overflow" -> "ellipsis", "max-width" -> "11em",
      "width" -> "12em"
    ))
    case x if List("updateTime").contains(x) => js.Dictionary("css" -> js.Dictionary(
      "white-space" -> "nowrap"
    ))
    case x if allSiteNames.contains(x) => js.Dictionary("css" -> js.Dictionary(
      "padding" -> 0
    ))
    case _ => v
  }

  def operateStyle: js.Function = (v: js.Any, row: js.Dictionary[Any]) => {
    js.Dictionary("css" -> js.Dictionary(
      "white-space" -> "nowrap"
    ))
  }

  def assignQueryMap = {
    queryMap = if (filterNonExist) {
      Map[String, Any]()
    } else {
      val filterMap = $(":input.filterInput").mapElems(y => y).map { y =>
        val name = $(y).attr("name").toString
        val v = if (name == "updateMission") {
          if ($(y).data("select2").isDefined) {
            $(y).select2Val
          } else ""
        } else {
          $(y).myVal
        }
        (name, v)
      }
        .toMap
      val eachParent = $("sup.sortSub").parents(".eachFCParent")
      val sortMap = if (eachParent.mapElems(y => y).isEmpty) {
        Map[String, String]()
      }
      else {
        val order = eachParent.attr("sort-type").toString
        val sort = Tool.getFilterDataFieldName(eachParent)
        Map("sort" -> sort, "order" -> order)
      }
      filterMap ++ sortMap
    }

  }

  @JSExport("confirmFilter")
  def confirmFilter(y: Element) = {
    assignQueryMap
    select2Vs = Tool.getInputByName("updateMission").select2Val
    hideFilterContent(y)
    showLoading
    refreshTable()
    fillConditionHtml
  }

  def refreshUpdateMission = {
    val url = g.jsRoutes.controllers.SampleController.getAllMissionName().url.toString
    Ajax.get(url = s"${
      url
    }").map {
      xhr =>
        val data = xhr.responseText.toJArS
        val array = data.map {
          v =>
            js.Dictionary("text" -> v, "id" -> v)
        }
        val options = Select2Options.multiple(true).allowClear(true).placeholder("点击选择").dictData(array)
        Tool.getInputByName("updateMission").select2(options)
    }
  }

  @JSExport("filterContentShow")
  def filterContentShow(y: Element) = {
    $(".filterContent").hide()
    val fieldName = getFilterDataFieldName(y)
    val contentId = s"${
      fieldName
    }Content"
    val yTop = $(y).offset().top - 113
    val pageWidth = document.body.clientWidth
    val yTotalLeft = $(y).offset().left
    val leftWidth = $("#myLeft").width()
    val yLeft = yTotalLeft - leftWidth
    val width = 210
    val trueYLeft = if (yTotalLeft + width > pageWidth) pageWidth - leftWidth - 220 - 6 else yLeft - 3
    $(s"#${
      contentId
    }").css("top", yTop.toInt).css("left", trueYLeft.toInt).width(width)
    $(s"#${
      contentId
    }").show()
  }

  @JSExport("hideFilterContent")
  def hideFilterContent(y: Element) = {
    val fieldName = Tool.getFilterDataFieldName($(y).parents(".filterContent"))
    if (fieldName == "updateTime") {
      val fieldNames = List("startTime", "endTime")
      fieldNames.foreach {
        fieldName =>
          Tool.getInputByName(fieldName).`val`(queryMap.get(fieldName).map(_.toString).getOrElse(""))
      }
    } else {
      val inputY = Tool.getInputByName(fieldName)
      if ($(inputY).hasClass("valueInput")) {
        if (inputY.data("select2").isDefined) {
          inputY.select2Val(queryMap.get(fieldName).map(_.toString).getOrElse(""))
        } else {
          inputY.`val`(queryMap.get(fieldName).map(_.toString).getOrElse(""))
        }
      }
    }

    Tool.getInputByName("updateMission").select2Val(select2Vs)
    $(y).parents(".filterContent").hide()
  }

  def getTrueInput(jq: JQuery) = {
    jq.mapElems(y => y).filter {
      y =>
        val isFixedColumns = $(y).parents().hasClass("fixed-columns")
        val isFixedColumnsRight = $(y).parents().hasClass("fixed-columns-right")
        !isFixedColumns && !isFixedColumnsRight
    }.head
  }

  def postBody: js.Function = () => {
    val numberJq = $("li.page-item").not(".page-next, .page-pre, .page-last-separator, .page-first-separator")
    numberJq.off("click").on("click", (y: Element, e: Event) => {
      $("#table").bootstrapTable("onPageNumber", e)
    })
  }

  def postHeader: js.Function = () => {

  }

  def getTableOptions(opColumnNames: List[String]) = {
    val basicColumns = List("id", "stepNum")
    val columnNames = basicColumns ::: opColumnNames
    val columns = js.Array(checkColumn) ++ columnNames.map {
      columnName =>
        val title = headerMap.getOrElse(columnName, columnName)
        val fmt = tbFmt(columnName)
        val style = expStyle(columnName)
        val columnsOptions = ColumnOptions.field(columnName).title(title).formatter(fmt).cellStyle(style)
        val basicOptions = columnName match {
          case _ => columnsOptions.sortable(false).operateable(false)
        }
        val datepickerOptions: js.Dictionary[js.Any] = js.Dictionary("format" -> Tool.pattern, "language" -> "zh-CN",
          "autoclose" -> true)
        val curAllSiteNames=VarTool.allSiteNames:::VarTool.emptySiteNames
        columnName match {
          case x if curAllSiteNames.contains(x) => basicOptions.`class`("siteTh").width(40)
          case x if List("interlocusBalance", "autosomalLociTyped", "yLociTyped", "xLociTyped", "isnpLociTyped").
            contains(x) => basicOptions.`class`("myInter").width(40)
          case _ => basicOptions
        }
    }.concat(operateColumn)
    val pageList = js.Array(30, 50, 100)
    val options = TableOptions.columns(columns).pageNumber(1).pagination(true).pageList(pageList).pageSize(pageList.head).
      fixedColumns(true).fixedNumber(2).fixedRightNumber(1).
      onSort(onSort).onLoadSuccess(onLoadSuccess).onPostBody(postBody).onPostHeader(postHeader)
      .height(1000)
    options
  }

  @JSExport("removeCondition")
  def removeCondition(y: Element) = {
    val fieldName = getFilterDataFieldName(y)
    if (fieldName == "updateTime") {
      Tool.getInputByName("startTime").`val`("")
      Tool.getInputByName("endTime").`val`("")
    } else {
      if (Tool.getInputByName(fieldName).hasClass("valueInput")) {
        Tool.getInputByName(fieldName).`val`("")
      } else if (Tool.getInputByName(fieldName).hasClass("select2Input")) {
        Tool.getInputByName(fieldName).select2Val(js.Array[String]())
        select2Vs = Tool.getInputByName("updateMission").select2Val
      }
    }

    fillConditionHtml
    execFilter
  }

  @JSExport("removeSort")
  def removeSort(y: Element) = {
    showLoading
    val fieldName = Tool.getFilterDataFieldName($(y).parents(".eachFCParent"))
    $("#sortCondition").html("")
    $("#sortCondition").parent().hide()
    $(s"button[filter-data-field=${
      fieldName
    }]").find(".afterSortFa").
      removeClass("fa-long-arrow-up").removeClass("fa-long-arrow-down")
    $(".myLi").removeClass("active")
    refreshTable()
  }

  def getMissionId = {
    g.missionId.toString
  }

  def initTable(kitName: String) = {
    val columnNames = List("containerName", "sampleIntro", "updateMission", "gender", "kind") ::: VarTool.siteNamesMap(kitName)
    val tableId = "table"
    val options = getTableOptions(columnNames)
    $(s"#${
      tableId
    }").bootstrapTable(options)
    bindEvt
    initFilter
    //      toggleFilter
    selectSiteNames(columnNames)
  }

  def selectSiteNames(siteNames: List[String]) = {
    siteNames.foreach {
      siteName =>
        $(s":input[value='${
          siteName
        }']").prop("checked", true)
    }
  }

  def initFilter = {
    registerFilter
    dateInit
  }

  @JSExport("exportAllDatShow")
  def exportAllDatShow = {
    $(s"#${exportAllDatModalId}").findInputByValue("SETA").setChecked
    $(s"#${exportAllDatModalId} #samples").html("所有查找结果")
    jQuery("#exportAllDatModal").modal("show")
  }

  def exportAllDat = {
    val bv = jQuery(s"#${exportAllDatModalId} #${formId}").data("bootstrapValidator")
    bv.validate()
    val valid = bv.isValid().toB
    if (valid) {
      val index = layer.alert(Tool.loadingElement, layerOptions)
      val exportDatMap = getExportDatMap(exportAllDatModalId)
      val data = (exportDatMap++Map("missionId" -> getMissionId)).toJSDictionary
      val url = g.jsRoutes.controllers.StepMissionController.exportAllDat().url.toString
      Ajax.post(url = s"${
        url
      }", data = JSON.stringify(data),
        headers = Map("Content-Type" -> "application/json"), responseType = "blob").map {
        xhr =>
          layer.close(index)
          jQuery(s"#${exportAllDatModalId}").modal("hide")
          if(exportDatMap("hasGroup").toB){
            Tool.downloadZip(s"${exportDatMap("kitName")}_all.zip",xhr.response)
          }else {
            Tool.downloadTxt(s"${exportDatMap("kitName")}_all.dat", xhr.response)
          }
      }
    }
  }

  @JSExport("operateFmt")
  def operateFmt: js.Function = {
    (v: js.Any, row: js.Dictionary[js.Any]) =>
      val downloadUrl = g.jsRoutes.controllers.SampleController.downloadReport().url.toString
      val downloadStr = a(title := "导出报告", href := s"${
        downloadUrl
      }?id=${
        row("id")
      }", cursor.pointer,
        span(em(cls := "fa fa-download"))
      )
      val exportStr = a(
        title := "导出dat文件",
        cursor.pointer,
        onclick := s"SampleManage.exportDtaShow('${row("id")}','${row("panel")}')",
        target := "_blank",
        span(
          em(cls := "fa fa-arrow-circle-right")
        )
      )
      Array(downloadStr, exportStr).mkString("&nbsp;")
  }

  def downloadZip(fileName: String, content: js.Any) = {
    val blob = new Blob(js.Array(content), BlobPropertyBag(`type` = "application/zip"))
    FileSaver.saveAs(blob, fileName)
  }

  @JSExport("exports")
  def exports = {
    val ids = getIdsValue
    val data = js.Dictionary(
      "ids" -> ids.toJSArray
    )
    val url = g.jsRoutes.controllers.SampleController.exportReports().url.toString
    val layerOptions = LayerOptions.title("正在导出报告").closeBtn(0).skin("layui-layer-molv").btn(js.Array())
    val index = layer.alert(Tool.myElement, layerOptions)
    Ajax.post(url = s"${url}", data = JSON.stringify(data),
      headers = Map("Content-Type" -> "application/json"), responseType = "blob").map { xhr =>
      layer.close(index)
      downloadZip("reports.zip", xhr.response)
    }
  }

  @JSExport("exportDtaShow")
  def exportDtaShow(id: String, panel: String) = {
    $("#samples").html(getSamplesHtml(List(id)))
    $(s"#${exportDatModalId}").findInputByValue(s"${panel}").setChecked
    jQuery(s"#${exportDatModalId}").modal("show")
  }

  def getSamplesHtml(ids: List[String]) = {
    ids.map {
      id =>
        label(
          marginRight := 15,
          width := checkWidth,
          cls := "myCheckbox mySamples",
          id
        )
    }.mkString
  }

  @JSExport("batchExportDtaShow")
  def batchExportDtaShow = {
    val idStr = getSamplesHtml(getIdsValue.toList)
    Tool.getInputByValue("SETA").setChecked
    $("#samples").html(idStr)
    jQuery(s"#${exportDatModalId}").modal("show")
  }

  @JSExport("deleteData")
  def deleteData(id: String) = {
    val options = SwalOptions.title("").text("确定要删除此数据吗？").`type`("warning").showCancelButton(true).
      showConfirmButton(true).confirmButtonClass(Tool.confirmButtonClass).confirmButtonText("确定").closeOnConfirm(false).
      cancelButtonText("取消").showLoaderOnConfirm(true).cancelButtonClass(Tool.cancelButtonClass)
    Swal.swal(options, () => {
      val url = g.jsRoutes.controllers.SampleController.deleteSampleById().url.toString
      Ajax.delete(url = s"${
        url
      }?id=${
        id
      }", headers = Map("Content-Type" -> "application/json")).map {
        xhr =>
          val data = xhr.response
          refreshTable {
            () =>
              Swal.swal(SwalOptions.title("成功").text("删除成功").`type`("success"))
          }
      }
    })
  }

  @JSExport("deletes")
  def deletes = {
    val ids = getIdsValue
    val options = SwalOptions.title("").text("确定要将选中的数据从库中移除吗？").`type`("warning").showCancelButton(true).
      showConfirmButton(true).confirmButtonClass(Tool.confirmButtonClass).confirmButtonText("确定").closeOnConfirm(false).
      cancelButtonText("取消").cancelButtonClass(Tool.cancelButtonClass)
    Swal.swal(options, () => {
      val data = js.Dictionary(
        "ids" -> ids.toJSArray
      )
      val url = g.jsRoutes.controllers.SampleController.deletes().url.toString
      Ajax.post(url = s"${
        url
      }", data = JSON.stringify(data),
        headers = Map("Content-Type" -> "application/json"), responseType = "blob").map {
        xhr =>
          refreshTable {
            () =>
              Swal.swal(SwalOptions.title("成功").text("移除成功！").`type`("success"))
              getIds
          }
      }
    })
  }

  def bootStrapValidator = {
    val maxNumber = Double.MaxValue


  }

}
